package com.yanqu.road.server.manger.activity.auto.send;

import com.yanqu.road.entity.activity.ActivityDetail;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eChannelRankActivityType;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.pb.activity.AutoSendRewardProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.utils.executor.GeneralThreadFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class AutoSendActivity extends TempMgr {
    private static ExecutorService threadPool = Executors.newFixedThreadPool(1, new GeneralThreadFactory("auto_send_reward"));
    private static Map<Integer, ActivityDetail> activityDetailMap = new ConcurrentHashMap<>();
    private static long lastAutoSendTime = 0;

    public static boolean isAutoSendRewardServer() {
        String[] split = ChannelConfig.AUTO_SEND_CROSS_RANK_REWARD_SERVER_PARAM.split("\\|");
        if (Integer.parseInt(split[0]) == 0) {
            return true;
        }
        String[] serverIds = split[1].split(";");
        return Arrays.stream(serverIds).anyMatch(s -> Long.valueOf(s) == GameServer.getInstance().getServerId());
    }

    public static boolean isAutoSendRewardActivity(ActivityInfo activityInfo) {

        // 这个活动不用补发
        if (activityInfo.getType() == eActivityType.ChannelRankActivity.getValue() && activityInfo.getChildType() == eChannelRankActivityType.ChannelWasheScoreSmallRank.getValue()) {
            return false;
        }

        String[] split = ChannelConfig.AUTO_SEND_CROSS_RANK_REWARD_ACTIVITY_PARAM.split("\\|");
        if (Integer.parseInt(split[0]) == 0) {
            return true;
        }
        String[] activityTypes = split[1].split(";");
        return Arrays.stream(activityTypes).anyMatch(s -> Long.valueOf(s) == activityInfo.getType());
    }

    public static void autoSendReward() {
        // 获取需要补发的活动列表
        try {
            ThreadPoolExecutor threadPool = (ThreadPoolExecutor) AutoSendActivity.threadPool;
            int size = threadPool.getQueue().size();
            if (size > 1000) {
                threadPool.getQueue().clear();
                getLogger().info("clear auto sendReward queue: {}", size);
            }
            long now = System.currentTimeMillis();
            if (now - lastAutoSendTime < 3600 * 1000L) {
                //1小时1次
                return;
            }
            lastAutoSendTime = now;
            getLogger().info("autoSendReward start: {}", now);

        } catch (Exception e) {
            getLogger().info("clear auto sendReward error", e);
        }
        List<ActivityInfo> activityInfoList = getNeedSendRewardActivityList();
        for (ActivityInfo info : activityInfoList) {
            if (!isAutoSendRewardActivity(info)) {
                continue;
            }
            BaseAutoSendActivity sendActivity = AutoSendActivityFactory.createAutoSendActivity(info);
            if (sendActivity != null) {
                sendActivity.sendConditionReward();
                sendActivity.sendLocalUserRankReward();
                sendActivity.sendLocalUnionRankReward();
                sendActivity.noticeCrossUserRank();
                sendActivity.noticeCrossUnionRank();
                sendActivity.noticeCrossTeamRank();
            }
        }
    }

    /**
     * 测排行自动发奖用的，其他地方不要用
     */
    public static void testAutoRank(){
        List<ActivityInfo> activityInfoList = getNeedSendRewardActivityList();
        for (ActivityInfo info : activityInfoList) {
            if (!isAutoSendRewardActivity(info)) {
                continue;
            }
            BaseAutoSendActivity sendActivity = AutoSendActivityFactory.createAutoSendActivity(info);
            if (sendActivity != null) {
                sendActivity.sendConditionReward();
                sendActivity.sendLocalUserRankReward();
                sendActivity.sendLocalUnionRankReward();
                sendActivity.noticeCrossUserRank();
                sendActivity.noticeCrossUnionRank();
            }
        }
    }

    private static List<ActivityInfo> getNeedSendRewardActivityList() {
        List<ActivityInfo> list = new ArrayList<>();
        for (ActivityDetail detail : activityDetailMap.values()) {
            if (detail.getAutoSendRewardState() == 0 || detail.getAutoSendRewardStateUnion() == 0) {
                long now = System.currentTimeMillis() / 1000;
                int activityId = detail.getActivityId();
                //未发奖，检测活动是否有效
                ActivityInfo activityInfo = getAutoSendActivityInfo(activityId);
                if (activityInfo == null) {
                    detail.setAutoSendRewardState(1);
                    detail.setAutoSendRewardStateUnion(1);
                    getLogger().error("getNeedSendRewardActivityList skip, can not find activityInfo id = {}", activityId);
                    continue; // 读不到活动，先不管
                }
                long endShowTime = activityInfo.getEndShowTime();
                if (now - endShowTime > 3600 * 24L * 7) {
                    //超出7天了 应该有问题，先不发
                    continue;
                }
                if (now < endShowTime + 3600) {
                    //结束一小时内， 也先不补发
                    continue;
                }
                list.add(activityInfo);
            }
        }
        return list;
    }

    private static ActivityInfo getAutoSendActivityInfo(int activityId) {
        // 读中心库
        ActivityInfo info = ActivityBussiness.getActivityInfoByActivityId(activityId);
        if (info != null) {
            return info;
        }

        // 读跨地区活动
        info = NormalActivityMgr.getAllActivityInfoMap().get(activityId);
        if (info != null && ActivityHelper.isCrossChannelActivityType(info.getType())) {
            return info;
        }

        getLogger().error("can not find activity id = {}", activityId);
        return null;
    }

    public static void addNeedAutoSendActivity() {
        long now = System.currentTimeMillis() / 1000;
        for (ActivityInfo info : ActivityMgr.getAllActivityInfos()) {
            int activityId = info.getActivityId();
            if (activityDetailMap.containsKey(activityId)) {
                continue;
            }
            if (!isAutoSendRewardActivity(info)) {
                continue;
            }
            if (info.getEndShowTime() - now < 6 * 3600 && info.getEndShowTime() > now) {
                ActivityDetail detail = new ActivityDetail();
                detail.setActivityId(activityId);
                detail.setAutoSendRewardState(0);
                detail.setInsertOption();
                activityDetailMap.put(info.getActivityId(), detail);
            }
        }
    }

    public static void sendCrossUserRankReward(AutoSendRewardProto.CrossUserRankMsg msg) {
        int activityId = msg.getActivityId();
        List<AutoSendRewardProto.UserRankMsg> dataList = msg.getDataList();
        ActivityInfo activityInfo = getAutoSendActivityInfo(activityId);
        if (activityInfo == null) {
            getLogger().error("sendCrossUserRankReward fail, can not find activityInfo id = {}", activityId);
            return;
        }
        BaseAutoSendActivity sendActivity = AutoSendActivityFactory.createAutoSendActivity(activityInfo);
        if (sendActivity != null) {
            threadPool.execute(() -> sendActivity.sendCrossUserRankReward(dataList));
        }
    }

    public static void changeSendState(int activityId, int type, int isSend) {
        ActivityDetail activityDetail = activityDetailMap.get(activityId);
        if (activityDetail != null) {
            if (type == 1) {
                activityDetail.setAutoSendRewardState(isSend);
            } else {
                activityDetail.setAutoSendRewardStateUnion(isSend);
            }
        }
    }

    public static void sendCrossUnionRankReward(AutoSendRewardProto.CrossUnionRankMsg msg) {
        int activityId = msg.getActivityId();
        List<AutoSendRewardProto.UnionRankMsg> dataList = msg.getDataList();
        ActivityInfo activityInfo = getAutoSendActivityInfo(activityId);
        if (activityInfo == null) {
            getLogger().error("sendCrossUnionRankReward fail, can not find activityInfo id = {}", activityId);
            return;
        }
        BaseAutoSendActivity autoSendActivity = AutoSendActivityFactory.createAutoSendActivity(activityInfo);
        if (autoSendActivity != null) {
            threadPool.execute(() -> autoSendActivity.sendCrossUnionRankReward(dataList));
        }
    }

    /**
     * 补发海上争霸联盟排行榜奖励
     * @param msg
     */
    @Deprecated
    public static void sendSeacraftSouthSeaUnionRankReward(AutoSendRewardProto.CrossUnionRankWithUnionInfoMsg msg) {
        int activityId = msg.getActivityId();
        List<AutoSendRewardProto.UnionRankWithUnionInfoMsg> dataList = msg.getDataList();
        ActivityInfo activityInfo = getAutoSendActivityInfo(activityId);
        if (activityInfo == null) {
            getLogger().error("sendCrossUnionRankReward fail, can not find activityInfo id = {}", activityId);
            return;
        }
        SeacraftSouthSeaActivityAutoSend southSeaActivityAutoSend = new SeacraftSouthSeaActivityAutoSend(activityInfo);
        if (southSeaActivityAutoSend != null) {
            threadPool.execute(() -> southSeaActivityAutoSend.sendSeacraftSouthSeaCrossUnionRankReward(dataList));
        }
    }


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        activityDetailMap = UserActivityBussiness.getCrossActivityDetailMap();
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        List<ActivityDetail> activityDetailList = new ArrayList<>(activityDetailMap.values());
        for (ActivityDetail activityDetail : activityDetailList) {
            if (activityDetail.isInsertOption()) {
                UserActivityBussiness.addCrossActivityDetail(activityDetail);
            } else if (activityDetail.isUpdateOption()) {
                UserActivityBussiness.updateCrossActivityDetail(activityDetail);
            }
        }
        return true;
    }
}
